/**
 * Created by admin on 2017/10/26.
 */
$(document).ready(function () {

    var compare = function (obj1, obj2) {
        var val1 = obj1.ope_id;
        var val2 = obj2.ope_id;
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    };

    var VAL = {
        TOOLG_ID    : "$FMA",
        NORMAL      : "0000000"  ,
        EVT_USER    : $("#userId").text(),
        T_FBPBISTOL : "FBPBISTOL",
        T_FBPBISPTH : "FBPBISPTH",
        T_FBPBISOPE : "FBPBISOPE",
        T_FBPBISDAT : "FBPBISDAT",
        T_FIPINQSHT : "FIPINQSHT",
        T_FPPMOVEIN : "FPPMOVEIN",
        T_FPPMOVEOUT: "FPPMOVEOUT",
        T_MIPINQMTRL: "MIPINQMTRL",
        T_MIPSHTJUDGE: "MIPSHTJUDGE",
        T_MPPREWORK : "MPPREWORK",

        DISABLED_ATTR: {
            'disabled': true
        },
        ENABLED_ATTR: {
            'disabled': false
        }
    };

    var domObj = {
        buttons : {
            $move_out_btn : $("#move_out_btn"),
            $clean_btn    : $("#clean_btn")
        },

        $opeIdSel        : $("#opeIdSel"),
        $toolIdSel       : $("#toolIdSel"),
        $prdSeqIdTxt     : $("#prdSeqIdTxt"),
        $radioOldMain    : $("#radioOldMain"),
        $radioFMA      : $("#radioFMA"),
        $defectCodeSel   : $("#defectCodeSel"),
        $remarkTxt       : $("#remarkTxt"),

        grids : {
            $prodListDiv : $("#prodListDiv"),
            $prodListGrd : $("#prodListGrd"),
            $prodListPg  : $("#prodListPg"),
            $mtrlListDiv : $("#mtrlListDiv"),
            $mtrlListGrd : $("#mtrlListGrd"),
            $mtrlListPg  : $("#mtrlListPg"),
            $defectJudgeDetailListDiv : $("#defectJudgeDetailListDiv"),
            $defectJudgeDetailListGrd : $("#defectJudgeDetailListGrd"),
            $defectJudgeDetailListPg : $("#defectJudgeDetailListPg")
        },

        dialogs: {
            $defectDialog : $("#defectDialog"),
            $defectDialog_defectTypeSel : $("#defectDialog_defectTypeSel"),
            $defectDialog_defectListDiv : $("#defectDialog_defectListDiv"),
            $defectDialog_defectListGrd : $("#defectDialog_defectListGrd"),
            $defectDialog_defectListPg : $("#defectDialog_defectListPg"),
            $defectDialog_sureBtn : $("#defectDialog_sureBtn")
        }
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function() {
        domObj.grids.$prodListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            autowidth: true,
            shrinkToFit: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            emptyrecords: true,
            colModel: [
                {
                    name: 'prd_seq_id',
                    index: 'prd_seq_id',
                    label: SHEET_ID_TAG,
                    width: 150
                },  {
                    name: 'prd_stat',
                    index: 'prd_stat',
                    label: PRD_STAT_TAG,
                    width: 100
                },{
                    name: 'prd_grade',
                    index: 'prd_grade',
                    label: PRD_GRADE_TAG,
                    width: 100
                }, {
                    name: 'lot_id_fk',
                    index: 'lot_id_fk',
                    label: LOT_ID_TAG,
                    width: 150
                }, {
                    name: 'wo_id_fk',
                    index: 'wo_id_fk',
                    label: WO_ID_TAG,
                    width: 150
                },{
                    name: 'mdl_id_fk',
                    index: 'mdl_id_fk',
                    label: MDL_ID_TAG,
                    width: 200
                }, {
                    name: 'path_id_fk',
                    index: 'path_id_fk',
                    label: PATH_ID_TAG,
                    width: 100
                }, {
                    name: 'path_ver_fk',
                    index: 'path_ver_fk',
                    label: PATH_VER_TAG,
                    width: 100
                }, {
                    name: 'ope_id_fk',
                    index: 'ope_id_fk',
                    label: OPE_ID_TAG,
                    width: 100
                }, {
                    name: 'ope_no_fk',
                    index: 'ope_no_fk',
                    label: OPE_NO_TAG,
                    width: 100
                },{
                    name: 'ope_ver_fk',
                    index: 'ope_ver_fk',
                    label: OPE_VER_TAG,
                    width: 100
                }, {
                    name: 'proc_id_fk',
                    index: 'proc_id_fk',
                    label: PROC_ID_TAG,
                    width: 100
                },{
                    name: 'tool_id_fk',
                    index: 'tool_id_fk',
                    label: TOOL_ID_TAG,
                    width: 100
                },{
                    name: 'logon_timestamp',
                    index: 'logon_timestamp',
                    label: LOGON_TIMESTAMP_TAG,
                    width: 180}],
            pager: "#prodListPg"
        });
        domObj.grids.$mtrlListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            autowidth: true,
            shrinkToFit: true,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            emptyrecords: true,
            colModel: [
                {
                    name: 'mtrl_cate',
                    index: 'mtrl_cate',
                    label: MTRL_CATE_TAG,
                    width: 100
                },  {
                    name: 'mtrl_prod_id_fk',
                    index: 'mtrl_prod_id_fk',
                    label: MTRL_ID_TAG,
                    width: 200
                },{
                    name: 'mtrl_batch',
                    index: 'mtrl_batch',
                    label: MTRL_LOT_ID_TAG,
                    width: 200
                }, {
                    name: 'mtrl_qty',
                    index: 'mtrl_qty',
                    label: MTRL_QTY_TAG,
                    width: 100
                }],
            pager: "#mtrlListPg"
        });
        domObj.grids.$defectJudgeDetailListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            autowidth: false,
            shrinkToFit: true,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            emptyrecords: true,
            colModel: [
                {
                    name: 'def_code',
                    index: 'def_code',
                    label: DEF_CODE_TAG,
                    width: 180
                }, {
                    name: 'def_code_desc',
                    index: 'def_code_desc',
                    label: DEF_DESC_TAG,
                    width: 350
                }],
            pager: "#defectJudgeDetailListPg"
        });
        domObj.dialogs.$defectDialog_defectListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            autowidth: false,
            shrinkToFit: true,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            emptyrecords: true,
            colModel: [
                {
                    name: 'data_id',
                    index: 'data_id',
                    label: DEF_CODE_TAG,
                    width: 180
                }, {
                    name: 'data_ext',
                    index: 'data_ext',
                    label: DEF_DESC_TAG,
                    width: 350
                }],
            pager: "#defectDialog_defectListPg"
        });
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resizeFnc : function(){
            var offsetBottom, grdDivWidth;
            grdDivWidth = $(".divTop").width();
            offsetBottom = $(window).height() - domObj.grids.$prodListDiv.offset().top;

            //prodList设置
            domObj.grids.$prodListDiv.width(grdDivWidth);
            domObj.grids.$prodListDiv.height(offsetBottom*0.17);
            domObj.grids.$prodListGrd.setGridWidth(grdDivWidth);
            domObj.grids.$prodListGrd.setGridHeight(offsetBottom*0.17-51);

            //mtrlList设置
            var grdDivWidth2 = $(".divTop2").width();
            var offsetBottom2 = $(window).height() - domObj.grids.$mtrlListDiv.offset().top;
            domObj.grids.$mtrlListDiv.width(grdDivWidth2);
            domObj.grids.$mtrlListDiv.height(offsetBottom2*0.4);
            domObj.grids.$mtrlListGrd.setGridWidth(grdDivWidth2);
            domObj.grids.$mtrlListGrd.setGridHeight(offsetBottom2*0.4-51);

            //mtrlList设置
            domObj.grids.$defectJudgeDetailListDiv.width(grdDivWidth2);
            domObj.grids.$defectJudgeDetailListDiv.height(offsetBottom2*0.4);
            domObj.grids.$defectJudgeDetailListGrd.setGridWidth(grdDivWidth2);
            domObj.grids.$defectJudgeDetailListGrd.setGridHeight(offsetBottom2*0.4-51);
        },
        iniOpeIdSel : function(){
            var inObj = {
                trx_id : VAL.T_FBPBISOPE,
                action_flg : "L"
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var oaryA = outObj.oary;
                oaryA.sort(compare);
                SelectDom.addSelectArr_(domObj.$opeIdSel, oaryA, "ope_id","ope_id","ope_dsc",true);
            }
        },
        iniToolIdSel : function(){
            var ope_id = $.trim(domObj.$opeIdSel.val());
            var inObj = {
                trx_id : VAL.T_FBPBISTOL,
                action_flg : "M",
                iary : [{
                    ope_id_fk   : ope_id
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr_(domObj.$toolIdSel, outObj.oary, "tool_id","tool_id","tool_dsc",true);
            }
        },
        /***************************初始化等级Dialog***************************/
        iniDefectDialogFunc : function(){
            /*****
             当多次弹出对话框的同时也会多次绑定click事件。
             解决办法: 在show Dialog时将click unbind全部掉
             然后再绑定，这样就只剩下一个click事件了。
             **********/
            domObj.dialogs.$defectDialog.unbind('shown.bs.modal');
            domObj.dialogs.$defectDialog_sureBtn.unbind('click');
            domObj.dialogs.$defectDialog_defectTypeSel.select2({
                theme : "bootstrap",
                width : $(window).width()* 0.12
            });
            domObj.dialogs.$defectDialog_sureBtn.bind('click', btnFunc.defect_sure_func);
            domObj.dialogs.$defectDialog.modal('show');
        },
        iniDefectInfo : function(){
            var inObj = {
                trx_id: VAL.T_FBPBISDAT,
                action_flg: "1",
                distinct_item : "EXT_2",
                iary: [{
                    data_cate : "DFCT"
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(domObj.dialogs.$defectDialog_defectTypeSel, outObj.oaryB, "distinct_data", "distinct_data", true, true);
            }else{
                return false;
            }
            if(!toolFunc.iniDefectListInfo()){
                return false;
            }
            return true;
        },
        iniDefectListInfo : function(){
            var inObj = {
                trx_id: VAL.T_FBPBISDAT,
                action_flg: "Q",
                iary: [{
                    data_cate : "DFCT",
                    ext_2 : $.trim(domObj.dialogs.$defectDialog_defectTypeSel.val())
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary, "#defectDialog_defectListGrd");
            }
        },
        iniPrdJudListInfo : function(){
            var prd_seq_id = $.trim(domObj.$prdSeqIdTxt.val());
            var inObj = {
                trx_id     : VAL.T_MIPSHTJUDGE,
                action_flg : "Q",
                prd_seq_id : prd_seq_id
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oaryA, "#defectJudgeDetailListGrd");
            }
        },
        queryPrdInfo : function(){
            var prd_seq_id = $.trim(domObj.$prdSeqIdTxt.val());
            if(!prd_seq_id){
                showErrorDialog("", "请输入屏体代码");
                return false;
            }
            var ope_id  = $.trim(domObj.$opeIdSel.val());
            var tool_id = $.trim(domObj.$toolIdSel.val());
            var inObj = {
                trx_id     : VAL.T_FIPINQSHT,
                action_flg : "Q",
                prd_seq_id : prd_seq_id
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj, "#prodListGrd");
                if(outObj.prd_stat == "WAIT" &&outObj.nx_toolg_id_fk == "$FMA"){
                    showErrorDialog("", "屏体站点为[" + outObj.ope_id_fk + "]，请去该站点入账");
                    return false;
                }
                if(outObj.prd_stat == "INPR" && outObj.cr_ope_id_fk  !== ope_id ){
                    showErrorDialog("", "屏体站点不匹配，屏体站点为[" + outObj.cr_ope_id_fk + "]");
                    return false;
                }
                if(outObj.prd_stat == "INPR" && outObj.cr_tool_id_fk  !== tool_id ){//WAIT状态没有设备代码
                    showErrorDialog("", "屏体设备不匹配，屏体设备为[" + outObj.cr_tool_id_fk + "]");
                    return false;
                }
                if(outObj.prd_stat !== "WAIT" && outObj.prd_stat !== "INPR"){
                    showErrorDialog("", "屏体状态不正确，必须为[WAIT]或者[INPR],当前状态为[" + outObj.prd_stat + "]");
                    return false;
                }else if(outObj.prd_stat == "WAIT"){
                    /*********************入账**********************/
                    if(!btnFunc.move_in_func(outObj)){
                        return false;
                    }
                }
                /*********************获取屏体绑定物料信息**********************/
                toolFunc.queryPrdMtrlInfo(prd_seq_id);
                /*********************初始化不良信息**********************/
                SelectDom.initWithSpace(domObj.dialogs.$defectDialog_defectTypeSel);
                domObj.dialogs.$defectDialog_defectListGrd.jqGrid("clearGridData");
                if(toolFunc.iniDefectInfo()){
                    return false;
                }
                /*********************初始化判定不良明细**********************/
                toolFunc.iniPrdJudListInfo();
            }else{
                return false;
            }
        },
        queryPrdMtrlInfo : function(prd_seq_id){
            var inObj = {
                trx_id     : VAL.T_MIPINQMTRL,
                action_flg : "Q",
                prd_seq_id : prd_seq_id
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary, "#mtrlListGrd");
            }
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        move_in_func : function(prdInfo){
            var prd_seq_id = $.trim(domObj.$prdSeqIdTxt.val());
            if(!prd_seq_id){
                showErrorDialog("", "请输入屏体代码");
                return false;
            }

            var tool_id = $.trim(domObj.$toolIdSel.val());
            if(!tool_id){
                showErrorDialog("", "请选择设备代码");
                return false;
            }

            var inObj = {
                trx_id     : VAL.T_FPPMOVEIN,
                evt_usr    : VAL.EVT_USER,
                action_flg : "A",
                opi_ope_flg: "Y",
                iary       : [{
                    prd_seq_id : prd_seq_id,
                    tool_id_fk : tool_id
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                prdInfo.prd_stat = "INPR";
                setGridInfo(prdInfo, "#prodListGrd");
            }else{
                return false;
            }

            return true;
        },
        clean_func: function () {
            iniContorlData();
            domObj.grids.$prodListGrd.jqGrid("clearGridData");
            domObj.grids.$mtrlListGrd.jqGrid("clearGridData");
            domObj.dialogs.$defectDialog_defectListGrd.jqGrid("clearGridData");
            domObj.dialogs.$gradeDialog_gradeListGrd.jqGrid("clearGridData");
        },
        defect_sure_func : function(){
            var rowId = domObj.dialogs.$defectDialog_defectListGrd.jqGrid('getGridParam','selrow');
            if(!rowId){
                showErrorDialog("", "请选择不良代码");
                return false;
            }
            var rowData = domObj.dialogs.$defectDialog_defectListGrd.jqGrid("getRowData", rowId);
            SelectDom.initWithValTxt(domObj.$defectCodeSel, rowData['data_id'], rowData['data_id']);
            domObj.dialogs.$defectDialog.modal('hide');
        },
        move_out_func : function(){
            var repair_flg;
            var rowIds = domObj.grids.$prodListGrd.jqGrid('getDataIDs');
            if(rowIds.length <= 0){
                showErrorDialog("","请输入需要出账的屏体代码，并按回车键获取屏体信息！");
                return false;
            }
            var rowData = domObj.grids.$prodListGrd.jqGrid('getRowData',rowIds[0]);
            var tool_id = $.trim(domObj.$toolIdSel.val());
            if(!tool_id){
                showErrorDialog("", "请选择设备代码");
                return false;
            }
            if(domObj.$radioFMA.attr("checked") == "checked"){
                repair_flg = "F";//判至到FMA
            }else{
                repair_flg = "O";//判至途程下一站点
            }
            var inObj = {
                trx_id     : VAL.T_MPPREWORK,
                evt_usr    : VAL.EVT_USER,
                action_flg : "M",
                repair_flg : repair_flg,
                iary       : [{
                    prd_seq_id : rowData['prd_seq_id'],
                    tool_id_fk : tool_id,
                    defect_code : $.trim(domObj.$defectCodeSel.val()),
                    sht_ope_msg : $.trim(domObj.$remarkTxt.val())
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                domObj.grids.$prodListGrd.jqGrid("clearGridData");
                domObj.grids.$mtrlListGrd.jqGrid("clearGridData");
                showMessengerSuccessDialog("出账成功！",1);
                domObj.$prdSeqIdTxt.val("");
                domObj.$prdSeqIdTxt.focus();
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        domObj.buttons.$clean_btn.click(function(){
            btnFunc.clean_func();
        });
        domObj.$radioOldMain.click(function(){
            btnFunc.radio_old_main_func();
        });
        domObj.$defectCodeSel.on("select2:opening",function(e){
            toolFunc.iniDefectDialogFunc();
        });
        domObj.buttons.$move_out_btn.click(function(){
            btnFunc.move_out_func();
        });
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        $("input").val("");
        SelectDom.initWithSpace($("select"));
        domObj.$radioOldMain.attr("checked","checked");
        toolFunc.iniOpeIdSel();
        toolFunc.iniToolIdSel();
    };

    var otherActionBind = function(){
        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });
        $(window).resize(function() {
            toolFunc.resizeFnc();
        });
        domObj.$prdSeqIdTxt.keydown(function(event){
            if(event.keyCode==13){
                toolFunc.queryPrdInfo();
            }
        });
        domObj.dialogs.$defectDialog_defectTypeSel.change(function(){
            toolFunc.iniDefectListInfo();
        });
        domObj.$opeIdSel.change(function(){
            toolFunc.iniToolIdSel();
        });
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        toolFunc.resizeFnc();
        iniContorlData();
        iniButtonAction();
        otherActionBind();
    };

    initializationFunc();
});
